/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.overall.modular.config.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.core.common.annotion.Permission;
import cn.stylefeng.guns.core.common.constant.Const;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.node.ZTreeNode;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.overall.modular.config.model.StandardArea;
import cn.stylefeng.overall.modular.config.service.IStandardAreaService;
import cn.stylefeng.overall.modular.config.wapper.StandardAreaWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 区域控制器
 *
 * @author fengshuonan
 * @Date 2017年2月12日21:59:14
 */
@Controller
@RequestMapping("/standardArea")
public class StandardAreaController extends BaseController {

    private static String PREFIX = "/config/standardArea/";

    @Autowired
    private IStandardAreaService standardAreaService;

    /**
     * 跳转到区域列表列表页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "standardArea.html";
    }

    /**
     * 跳转到区域列表列表页面
     */
    @RequestMapping(value = "/standardArea_add")
    public String standardAreaAdd() {
        return PREFIX + "standardArea_add.html";
    }

    /**
     * 跳转到区域详情列表页面
     */
    @Permission(Const.ADMIN_NAME)
    @RequestMapping(value = "/standardAreadit/{standardAreaId}")
    public String standardAreaEdit(@PathVariable Long standardAreaId, Model model) {
        if (ToolUtil.isEmpty(standardAreaId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        StandardArea standardArea = this.standardAreaService.selectById(standardAreaId);

        //获取父级区域的id
        StandardArea temp = new StandardArea();
        temp.setId(standardArea.getParentId());
        StandardArea pstandardArea = this.standardAreaService.selectOne(new EntityWrapper<>(temp));

        //如果父级是顶级区域
        if (pstandardArea == null) {
            standardArea.setParentId("");
        } else {
            //设置父级区域的code为父级区域的id
            standardArea.setParentId(String.valueOf(pstandardArea.getId()));
        }

        Map<String, Object> standardAreaMap = BeanUtil.beanToMap(standardArea);
        //standardAreaMap.put("pcodeName", ConstantFactory.me().getStandardAreaNameByCode(temp.getCode()));
        model.addAttribute("standardArea", standardAreaMap);
        LogObjectHolder.me().set(standardArea);
        return PREFIX + "standardArea_edit.html";
    }

    /**
     * 修该区域
     */
    @Permission(Const.ADMIN_NAME)
    @RequestMapping(value = "/edit")
    @ResponseBody
    public ResponseData edit(@Valid StandardArea standardArea, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //设置父级区域编号
        standardAreaSetPcode(standardArea);

        this.standardAreaService.updateById(standardArea);
        return SUCCESS_TIP;
    }

    /**
     * 获取区域列表
     */
    @Permission(Const.ADMIN_NAME)
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String standardAreaName) {
        List<Map<String, Object>> standardAreas = this.standardAreaService.selectAreas(standardAreaName);
        return super.warpObject(new StandardAreaWarpper(standardAreas));
    }

    /**
     * 新增区域
     */
    @Permission(Const.ADMIN_NAME)
    @RequestMapping(value = "/add")
    @ResponseBody
    public ResponseData add(@Valid StandardArea standardArea, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }

        //设置父级区域编号
        standardAreaSetPcode(standardArea);

        standardArea.setIsDelete("N");
        this.standardAreaService.insert(standardArea);
        return SUCCESS_TIP;
    }

    /**
     * 删除区域
     */
    @Permission(Const.ADMIN_NAME)
    @RequestMapping(value = "/remove")
    @ResponseBody
    public ResponseData remove(@RequestParam String standardAreaId) {
        if (ToolUtil.isEmpty(standardAreaId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }


        this.standardAreaService.delAreaContainSubAreas(standardAreaId);
        return SUCCESS_TIP;
    }

    /**
     * 查看区域
     */
    @RequestMapping(value = "/view/{standardAreaId}")
    @ResponseBody
    public ResponseData view(@PathVariable Long standardAreaId) {
        if (ToolUtil.isEmpty(standardAreaId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.standardAreaService.selectById(standardAreaId);
        return SUCCESS_TIP;
    }

    /**
     * 获取区域列表(首页用)
     */
    @RequestMapping(value = "/standardAreaTreeList")
    @ResponseBody
    public List<ZTreeNode> standardAreaTreeList() {
        return this.standardAreaService.areaTreeList();
    }

    /**
     * 获取区域列表(选择父级区域用)
     */
    @RequestMapping(value = "/selectstandardAreaTreeList")
    @ResponseBody
    public List<ZTreeNode> selectstandardAreaTreeList() {
        List<ZTreeNode> roleTreeList = this.standardAreaService.areaTreeList();
        roleTreeList.add(ZTreeNode.createParent());
        return roleTreeList;
    }

    /**
     * 根据请求的父级区域编号设置pcode和层级
     */
    private void standardAreaSetPcode(@Valid StandardArea standardArea) {
        if (ToolUtil.isEmpty(standardArea.getParentId()) || standardArea.getParentId().equals("0")) {
            standardArea.setParentId("0");
            standardArea.setPath("[0],");
        } else {
            String id = standardArea.getParentId();
            StandardArea pstandardArea = standardAreaService.selectById(id);
            standardArea.setParentId(pstandardArea.getId());

            //如果编号和父编号一致会导致无限递归
            if (standardArea.getCode().equals(standardArea.getParentId())) {
                throw new ServiceException(BizExceptionEnum.DB_RESOURCE_NULL);
            }

            standardArea.setParentId(pstandardArea.getParentId() + "[" + pstandardArea.getId() + "],");
        }
    }

}
